<template>
  <div
    class="ExamIndexContainer"
    @contextmenu.prevent="handleContextMenu($event)"
    @mouseup="handleMouseUp($event)"
  >
    <div class="ExamBox">
      <Aircle></Aircle>
      <AnswerHeader></AnswerHeader>
      <ReferenceAnalysis></ReferenceAnalysis>
      <Note :title="title"></Note>
      <VideoAnalysis></VideoAnalysis>
      <Discuss></Discuss>
      <MaskEditor></MaskEditor>
    </div>
    <div
      v-if="contextMenuVisible"
      class="context-menu"
      :style="{
        left: contextMenuPosition.x + 'px',
        top: contextMenuPosition.y + 'px',
      }"
    >
      <ul>
        <li v-if="showIncremental" @click="addToVocabulary">添加生词表</li>
        <li v-if="showIncrementalText" @click="addToSentenceList">添加长短句</li>
      </ul>
    </div>
    <!-- kaishi -->
    <!-- 购买弹窗 -->
    <CommonModal
      v-model="showPurchaseModal"
      title="云帆美研线上模考须知"
      :showPricing="true"
      :showTrialInfo="true"
      :productInfo="{
        trialDays: 34,
        examDays: 66,
      }"
      :priceOptions="priceOptions"
      totalPrice="555.00"
      purchaseButtonText="去购买"
      @purchase="handlePurchase"
    />
    <CommonModal
      v-model="showTimeModal"
      title="选择考试限时规则"
      description="滚动鼠标选择您需要限制的最长答题时间，倒计时结束后将自动为您完成交卷"
      :showTimeSelect="true"
      :showConfirmButtonOK="true"
      @time-select="handleTimeSelect"
    />

    <!-- 试用信息弹窗 -->
    <CommonModal
      v-model="showTrialModal"
      title="云帆美研线上模考须知"
      :showTrialInfo="true"
      :trialCount="0"
      :fullExamCount="2"
      :showActionButtons="true"
      @trial="handleTrial"
      @purchase="handlePurchase"
    />
  </div>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import { getWordList } from "~/service/banner.js";
import { useRouter } from "vue-router";
import Aircle from "./aircle/index.vue";
import AnswerHeader from "./answerHeader/index.vue";
import Note from "./Note/index.vue";
import ReferenceAnalysis from "./referenceAnalysis/index.vue";
import Discuss from "./discuss/index.vue";
import VideoAnalysis from "./videoAnalysis/index.vue";
import MaskEditor from "@/components/CommentEdit/index.vue";
import { userEditorStore } from "@/stores/editor.js";
import { useExam } from "@/stores/exam.js";
import { useTimer } from "@/stores/timer.js";
import { getExamDetail, getQuestionDetail } from "@/service/exam.js";
import { ElLoading } from "element-plus";
import CommonModal from "@/components/commModel.vue";
const userEditor = userEditorStore();
const examStore = useExam();
const timerStore = useTimer();
const showIncremental = ref(false);
const showIncrementalText = ref(false);
const title = "我的笔记";
const router = useRouter();

const contextMenuVisible = ref(false);
const contextMenuPosition = ref({ x: 0, y: 0 });
const selectedText = ref("");
const priceOptions = ref([
  {
    label: "还原真题",
    children: [
      { amount: "99", period: "月", discount: "9" },
      { amount: "287", period: "3个月", discount: "9" },
      { amount: "475", period: "6个月", discount: "9" },
      { amount: "623", period: "9个月", discount: "9" },
      { amount: "712", period: "12个月", discount: "9" },
    ],
  },
  {
    label: "全真模拟",
    children: [{ amount: "99", period: "年", discount: "" }],
  },
]);
// tognyong MOdal
const showTimeModal = ref(false);
const showTrialModal = ref(false);
const showPurchaseModal = ref(false);
const loading = ref(null);

const handleTimeSelect = (time) => {
  console.log("Selected time:", time);
};

const handleTrial = () => {
  console.log("Start trial");
};

const handlePurchase = () => {
  console.log("Go to purchase");
};

// 获取试题详情
const getQuestionDetailFn = async (data, secIndex, index) => {
  let currQuestion;
  if (examStore.examInfo.type3 == 3 || examStore.examInfo.type3 == 5) {
    currQuestion = {
      ...data?.section?.[secIndex].question[index],
      sectionIndex: secIndex,
      index,
    };
  } else {
    currQuestion = {
      ...data?.section?.[secIndex].question.find((it) => it.is_answer == 0),
      sectionIndex: secIndex,
      index,
    };
  }

  if (currQuestion.id) {
    // 题目详情

    const quesRes = await getQuestionDetail({
      qid: currQuestion.id,
      subject: examStore.examInfo.subject || 1,
      examid: examStore.examInfo.examid,
      paperid: examStore.examInfo.paperid,
    });

    loading.value && loading.value.close();
    if (quesRes.code == "000000") {
      console.log(quesRes, "quesRes======");
      timerStore.quesTimeStart();
      timerStore.paperTimeStart(data.time);
      examStore.currQuestion = { ...currQuestion, ...quesRes.data, showAnswer: false };
    }
  }
};

//获取基础信息
const handleExamDetail = async () => {
  try {
    if (examStore.examInfo.type3 == 3 || examStore.examInfo.type3 == 5) {
      // 顺序练习、高阶练习不需要获取试卷详情
      getQuestionDetailFn(examStore.examInfo, 0, 0);
      return;
    }
    // 试卷详情
    const examRes = await getExamDetail({
      examid: examStore.examInfo.examid,
      paperid: examStore.examInfo.paperid,
    });
    console.log(examRes, "examRes==");
    if (examRes.code === "000000") {
      examStore.examInfo = examRes.data;

      // 寻找第一个未答题的question
      let sectionIndex = -1;
      let index = -1;
      examRes.data.section.forEach((sec, secIndex) => {
        const questionIndex = sec.question.findIndex((it) => it.is_answer == 0);
        if (questionIndex !== -1 && index == -1) {
          sectionIndex = secIndex;
          index = questionIndex;
        }
      });

      getQuestionDetailFn(examRes.data, sectionIndex, index);
    }
  } catch (error) {
    console.log(error, "error==");
  }
};
//添加长短句或短句
const getWordListData = async ({ qid, title, type }) => {
  try {
    const res = await getWordList({
      qid: examStore.currQuestion.id,
      title: title,
      type: type,
    });
    console.log(res, "res==");
  } catch (error) {
    console.log(error, "error==");
  }
};

// end
// 处理右键菜单事件
const handleContextMenu = (event) => {
  showContextMenu(event);
};

// 处理鼠标按键事件
const handleMouseUp = (event) => {
  // 检查是否是右键点击（button === 2）或 Mac 触控板右击
  if (event.button === 2 || event.ctrlKey) {
    showIncrementalText.value = false;
    showIncrementalText.value = false;
    showContextMenu(event);
  }
};

// 处理弹窗提交
const handleDialogSubmit = (content) => {
  console.log("提交的内容:", content);
  // 这里处理提交逻辑
};

const isSentence = (text) => {
  // 1. 检查是否包含标点符号
  const punctuationRegex = /[.!?。！？，,]/;

  // 2. 检查是否包含多个单词（通过空格分割）
  // 先去除多余空格，然后分割
  const words = text.replace(/\s+/g, " ").trim().split(" ");

  // 如果包含标点符号 或 包含多个单词，则认为是句子
  return punctuationRegex.test(text) || words.length > 1;
};
const showContextMenu = (event) => {
  const selection = window.getSelection();
  const text = selection.toString().trim();

  if (text) {
    selectedText.value = text;
    if (isSentence(text)) {
      showIncrementalText.value = true;
      showIncremental.value = false;
      console.log("---1");
    } else {
      console.log("---2");
      showIncremental.value = true;
      showIncrementalText.value = false;
    }

    // 直接使用鼠标事件坐标
    contextMenuPosition.value = {
      x: event.clientX,
      y: event.clientY,
    };

    contextMenuVisible.value = true;
    event.preventDefault();
  } else {
    contextMenuVisible.value = false;
  }
};

// 修改隐藏菜单的逻辑，添加判断以避免立即隐藏
const hideContextMenu = (event) => {
  // 检查点击是否在菜单外部
  const menu = document.querySelector(".context-menu");
  if (menu && !menu.contains(event.target)) {
    contextMenuVisible.value = false;
  }
};

// 在组件挂载时添加点击事件监听
onMounted(() => {
  loading.value = ElLoading.service({
    target: ".admin-wrapper",
    lock: true,
    text: "Loading",
    background: "rgba(255, 255, 255, 0.7)",
  });

  document.addEventListener("click", hideContextMenu);
  // 禁用默认的上下文菜单
  document.addEventListener("contextmenu", (e) => e.preventDefault());
  handleExamDetail();
});

// 在组件卸载时移除事件监听
onUnmounted(() => {
  document.removeEventListener("click", hideContextMenu);
});

const addToVocabulary = () => {
  if (selectedText.value) {
    console.log("添加到生词表:", selectedText.value);
    contextMenuVisible.value = false;
    getWordListData({ pid: 1, title: selectedText.value, type: 1 });

    // router.push({
    //   path: "/vocabulary-page",
    //   query: { word: selectedText.value },
    // });
  }
};

const addToSentenceList = () => {
  if (selectedText.value) {
    console.log("添加到长短句:", selectedText.value);
    getWordListData({ pid: 1, title: selectedText.value, type: 2 });
    contextMenuVisible.value = false;

    // router.push({
    //   path: "/personCenter",
    //   query: { sentence: selectedText.value, personCenterValue: 2 },
    // });
  }
};

const handleUpdate = (flag) => {
  EditorComponents.value[current] = flag;
};
const questions = ref([
  {
    question: "1+1=?",
    answer: "1",
    status: "todo",
  },
  {
    question: "1+1=?",
    answer: "2",
    status: "done",
  },
  {
    question: "1+1=?",
    answer: "3",
    status: "wrong",
  },
  {
    question: "1+1=?",
    answer: "4",
    status: "correct",
  },
  {
    question: "1+1=?",
    answer: "5",
    status: "todo",
  },
  {
    question: "1+1=?",
    answer: "6",
    status: "todo",
  },
  {
    question: "1+1=?",
    answer: "5",
    status: "todo",
  },
  {
    question: "1+1=?",
    answer: "6",
    status: "todo",
  },
  {
    question: "1+1=?",
    answer: "5",
    status: "todo",
  },
  {
    question: "1+1=?",
    answer: "6",
    status: "todo",
  },
  {
    question: "1+1=?",
    answer: "5",
    status: "todo",
  },
  {
    question: "1+1=?",
    answer: "6",
    status: "todo",
  },
  {
    question: "1+1=?",
    answer: "5",
    status: "todo",
  },
  {
    question: "1+1=?",
    answer: "6",
    status: "todo",
  },
  {
    question: "1+1=?",
    answer: "5",
    status: "todo",
  },
  {
    question: "1+1=?",
    answer: "6",
    status: "todo",
  },
]);
// exel
</script>
<style lang="scss" scoped>
.ExamIndexContainer {
  display: flex;
  justify-content: center;
  position: relative;
  -webkit-user-select: text;
  user-select: text;

  .ExamBox {
    width: 1000px;
  }
}

.context-menu {
  position: fixed;
  background-color: white;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  min-width: 120px;
  user-select: none;

  ul {
    list-style: none;
    margin: 0;
    padding: 4px 0;

    li {
      padding: 8px 16px;
      cursor: pointer;
      font-size: 14px;
      white-space: nowrap;

      &:hover {
        background-color: #f5f5f5;
      }
    }
  }
}
</style>
